/**
 * 角色权限关联服务
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { Role } from './entities/role.entity';
import { Permission } from '../permission/entities/permission.entity';

@Injectable()
export class RolePermissionService {
  constructor(
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>,
    @InjectRepository(Permission)
    private readonly permissionRepository: Repository<Permission>,
  ) {}

  /**
   * 为角色分配权限
   * @param roleId 角色ID
   * @param permissionIds 权限ID列表
   */
  async assignPermissions(roleId: number, permissionIds: number[]): Promise<void> {
    const role = await this.roleRepository.findOne({
      where: { id: roleId, is_deleted: 0 },
    });

    if (!role) {
      throw new NotFoundException(`ID为${roleId}的角色不存在`);
    }

    const permissions = await this.permissionRepository.findBy({
      id: In(permissionIds),
      is_deleted: 0,
    });

    role.permissions = permissions;
    await this.roleRepository.save(role);
  }

  /**
   * 获取角色的权限列表
   * @param roleId 角色ID
   * @returns Promise<Permission[]> 权限列表
   */
  async getRolePermissions(roleId: number): Promise<Permission[]> {
    const role = await this.roleRepository.findOne({
      where: { id: roleId, is_deleted: 0 },
      relations: ['permissions'],
    });

    if (!role) {
      throw new NotFoundException(`ID为${roleId}的角色不存在`);
    }

    return role.permissions;
  }

  /**
   * 移除角色的权限
   * @param roleId 角色ID
   * @param permissionIds 权限ID列表
   */
  async removePermissions(roleId: number, permissionIds: number[]): Promise<void> {
    const role = await this.roleRepository.findOne({
      where: { id: roleId, is_deleted: 0 },
      relations: ['permissions'],
    });

    if (!role) {
      throw new NotFoundException(`ID为${roleId}的角色不存在`);
    }

    role.permissions = role.permissions.filter(
      permission => !permissionIds.includes(permission.id)
    );
    await this.roleRepository.save(role);
  }
} 